package com.mucd.userservice.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mucd.blog.entity.MyUserEntity;
import com.mucd.blog.result.R;
import com.mucd.blog.statuscode.MyException;
import com.mucd.blog.statuscode.StatusCode;
import com.mucd.blog.util.PasswordUtil;
import com.mucd.blog.util.ThreadLocalUtils;
import com.mucd.userservice.dao.UserDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author mucd
 */
@Slf4j
@Service
public class UserRegisterServiceImpl {


    @Resource
    private UserDao userDao;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 注册用户
     *
     * @return R
     */
    public R register() {

        MyUserEntity user = ThreadLocalUtils.get("user");

        QueryWrapper<MyUserEntity> qw = new QueryWrapper<>();
        qw.eq("user_name", user.getUserName());

        List<MyUserEntity> myUserEntities = userDao.selectList(qw);

        //null true
        if (ObjectUtil.isNull(myUserEntities)) {
            return R.error("用户{" + user.getUserName() + "}已存在");
        }

        //加密密码,把加密后的密码存进去
        String encrypt = PasswordUtil.encrypt(user.getUserPassword());
        user.setUserPassword(encrypt);

        int insert = userDao.insert(user);
        if (insert > 0) {
            return R.ok(insert);
        }

        throw new MyException(StatusCode.EXCEPTION_ERROR);
    }
}
